package com.jiezhuo.listener;

import com.jiezhuo.websocket.NoticeWebsocket;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
public class FileListener extends FileAlterationListenerAdaptor {


    @Override
    public void onStart(FileAlterationObserver observer) {
        super.onStart(observer);
        // System.out.println("一轮轮询开始，被监视路径：" + observer.getDirectory());
    }

    @Override
    public void onDirectoryCreate(File directory) {
        System.out.println("创建文件夹：" + directory.getAbsolutePath());
    }

    @Override
    public void onDirectoryChange(File directory) {
        System.out.println("修改文件夹：" + directory.getAbsolutePath());
    }

    @Override
    public void onDirectoryDelete(File directory) {
        System.out.println("删除文件夹：" + directory.getAbsolutePath());
    }

    @Override
    public void onFileCreate(File file) {
        String compressedPath = file.getAbsolutePath();
        System.out.println("新建文件：" + compressedPath);
        if (file.canRead()) {
            // TODO 读取或重新加载文件内容
            System.out.println("文件变更，进行处理");
        }
    }

    @Override
    public void onFileChange(File file) {
        StringBuffer stringBuffer=new StringBuffer();
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader(file); // 创建 FileReader 对象
            br = new BufferedReader(fr); // 创建 BufferedReader 对象
            String strLine = "";
            while ((strLine = br.readLine()) != null) { // 循环读取每行数据
                stringBuffer.append(strLine+"\n") ;
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fr.close(); // 关闭 FileReader 对象
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String compressedPath = file.getAbsolutePath();
        NoticeWebsocket.sendMessage(stringBuffer.toString());
        System.out.println( stringBuffer.toString());
    }

    @Override
    public void onFileDelete(File file) {
        System.out.println("删除文件：" + file.getAbsolutePath());
    }

    @Override
    public void onStop(FileAlterationObserver observer) {
        super.onStop(observer);
        // System.out.println("一轮轮询结束，被监视路径：" + fileAlterationObserver.getDirectory());
    }
}
